<template>
  <div class="test-container">
    <h2>API 测试页面</h2>
    
    <div class="test-section">
      <h3>快速登录测试</h3>
      <div class="login-form">
        <el-input v-model="testUsername" placeholder="用户名" style="margin-bottom: 10px;" />
        <el-input v-model="testPassword" placeholder="密码" type="password" style="margin-bottom: 10px;" />
        <el-button @click="quickLogin" :loading="loggingIn" type="primary">
          快速登录
        </el-button>
        <el-button @click="clearLoginData" type="danger" style="margin-left: 10px;">
          清除登录数据
        </el-button>
      </div>
      <div v-if="loginResult" class="result">
        <pre>{{ loginResult }}</pre>
      </div>
    </div>
    
    <div class="test-section">
      <h3>用户登录状态测试</h3>
      <el-button @click="testUserStatus" :loading="testingUser">
        测试用户状态
      </el-button>
      <el-button @click="forceRefreshUserStore" type="warning" style="margin-left: 10px;">
        强制刷新用户状态
      </el-button>
      <div v-if="userResult" class="result">
        <pre>{{ userResult }}</pre>
      </div>
    </div>
    
    <div class="test-section">
      <h3>后端连接测试</h3>
      <el-button @click="testBackendConnection" :loading="testing">
        测试后端连接
      </el-button>
      <div v-if="testResult" class="result">
        <pre>{{ testResult }}</pre>
      </div>
    </div>
    
    <div class="test-section">
      <h3>草稿API测试</h3>
      <el-button @click="testDraftAPI" :loading="testingDraft">
        测试草稿API
      </el-button>
      <div v-if="draftResult" class="result">
        <pre>{{ draftResult }}</pre>
      </div>
    </div>
    
    <div class="test-section">
      <h3>草稿保存测试</h3>
      <el-button @click="testDraftSave" :loading="testingDraftSave">
        测试草稿保存
      </el-button>
      <div v-if="draftSaveResult" class="result">
        <pre>{{ draftSaveResult }}</pre>
      </div>
    </div>
    
    <div class="test-section">
      <h3>分类API测试</h3>
      <el-button @click="testCategoryAPI" :loading="testingCategory">
        测试分类API
      </el-button>
      <div v-if="categoryResult" class="result">
        <pre>{{ categoryResult }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const testUsername = ref('admin')
const testPassword = ref('123456')
const loggingIn = ref(false)
const loginResult = ref('')

const testing = ref(false)
const testingUser = ref(false)
const testingDraft = ref(false)
const testingDraftSave = ref(false)
const testingCategory = ref(false)
const testResult = ref('')
const userResult = ref('')
const draftResult = ref('')
const draftSaveResult = ref('')
const categoryResult = ref('')

// 快速登录
const quickLogin = async () => {
  loggingIn.value = true
  try {
    const params = new URLSearchParams()
    params.append('username', testUsername.value)
    params.append('password', testPassword.value)

    const response = await axios.post('/app/auth/login', params)
    
    if (response.data.code === 200) {
      const { token, userName, avatar, userType, id } = response.data.data
      userStore.setToken(token)
      userStore.setUserInfo({
        userName,
        avatar: avatar || '',
        userType,
        id
      })
      
      loginResult.value = JSON.stringify(response.data, null, 2)
      ElMessage.success('登录成功')
    } else {
      loginResult.value = JSON.stringify(response.data, null, 2)
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    loginResult.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data, null, 2)}`
    ElMessage.error('登录失败')
  } finally {
    loggingIn.value = false
  }
}

// 清除登录数据
const clearLoginData = () => {
  userStore.logout()
  loginResult.value = '登录数据已清除'
  ElMessage.success('登录数据已清除')
}

// 强制刷新用户状态
const forceRefreshUserStore = () => {
  // 重新从localStorage读取数据
  const token = localStorage.getItem('token')
  const userId = localStorage.getItem('userId')
  const userInfo = localStorage.getItem('userInfo')
  
  if (token) userStore.setToken(token)
  if (userId) userStore.setUserId(userId)
  if (userInfo) {
    try {
      userStore.setUserInfo(JSON.parse(userInfo))
    } catch (error) {
      console.error('解析userInfo失败:', error)
    }
  }
  
  userResult.value = '用户状态已强制刷新\n' + JSON.stringify(userStore.getDebugInfo(), null, 2)
  ElMessage.success('用户状态已强制刷新')
}

// 测试用户状态
const testUserStatus = async () => {
  testingUser.value = true
  try {
    const debugInfo = userStore.getDebugInfo()
    userResult.value = JSON.stringify(debugInfo, null, 2)
    ElMessage.success('用户状态获取成功')
  } catch (error) {
    userResult.value = `错误: ${error.message}`
    ElMessage.error('用户状态获取失败')
  } finally {
    testingUser.value = false
  }
}

// 测试后端连接
const testBackendConnection = async () => {
  testing.value = true
  try {
    const response = await axios.get('/app/news/list', {
      params: { pageNo: 1, pageSize: 5 }
    })
    testResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('后端连接成功')
  } catch (error) {
    testResult.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data, null, 2)}`
    ElMessage.error('后端连接失败')
  } finally {
    testing.value = false
  }
}

// 测试草稿API
const testDraftAPI = async () => {
  testingDraft.value = true
  try {
    const response = await axios.get('/app/news/draft/list', {
      params: { page: 1, size: 5, authorId: userStore.userId || 1 }
    })
    draftResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('草稿API测试成功')
  } catch (error) {
    draftResult.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data, null, 2)}`
    ElMessage.error('草稿API测试失败')
  } finally {
    testingDraft.value = false
  }
}

// 测试草稿保存
const testDraftSave = async () => {
  testingDraftSave.value = true
  try {
    if (!userStore.isLoggedIn()) {
      draftSaveResult.value = '错误: 用户未登录，无法保存草稿\n调试信息: ' + JSON.stringify(userStore.getDebugInfo(), null, 2)
      ElMessage.error('用户未登录')
      return
    }

    const draftData = {
      categoryId: 1,
      title: '测试草稿标题',
      summary: '这是一个测试草稿的摘要',
      content: '<p>这是一个测试草稿的内容</p>',
      picPath: '',
      authorId: parseInt(userStore.userId)
    }

    const response = await axios.post('/app/news/draft/save', draftData)
    draftSaveResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('草稿保存测试成功')
  } catch (error) {
    draftSaveResult.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data, null, 2)}`
    ElMessage.error('草稿保存测试失败')
  } finally {
    testingDraftSave.value = false
  }
}

// 测试分类API
const testCategoryAPI = async () => {
  testingCategory.value = true
  try {
    const response = await axios.get('/app/categories')
    categoryResult.value = JSON.stringify(response.data, null, 2)
    ElMessage.success('分类API测试成功')
  } catch (error) {
    categoryResult.value = `错误: ${error.message}\n${JSON.stringify(error.response?.data, null, 2)}`
    ElMessage.error('分类API测试失败')
  } finally {
    testingCategory.value = false
  }
}
</script>

<style scoped>
.test-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.test-section h3 {
  margin-top: 0;
  color: #333;
}

.login-form {
  margin-bottom: 15px;
}

.result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.result pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style> 